package com.algrithom.stack;

import java.util.Objects;
import java.util.Stack;

/**
 * 最长有效括号
 *
 * @author think
 * @version 1.0.0
 * @since 2020/1/12
 */
public class Solution2 {
    
    public static void main(String[] args){
        System.out.println(longestAvaStr(")()()()"));
        System.out.println(longestAvaStr(")(())"));
    }
    
    private static int longestAvaStr(String str){
        if (Objects.isNull(str) || str.length() == 0) {
            return 0;
        }
        int len = str.length();
        char[] chars = str.toCharArray();
        int result = 0;
        Stack<Integer> stack = new Stack<>();
        stack.push(-1);
        for (int i = 0; i < len; i++) {
            if (chars[i] == ')' && stack.size() > 1 && chars[stack.peek()] == '(') {
                stack.pop();
                result = Math.max(result,i - stack.peek());
            } else {
                stack.push(i);
            }
        }
        return result;
    }
}
